/* 
 * File:   SpeakerHandler.cpp
 * Author: Alex
 * 
 * Created on 15 juni 2012, 13:08
 */

#include "SpeakerHandler.h"

void SpeakerHandler::main(void) {

    std::cout << "\n Speaker starting ";

    state = SpeakerWaiting;

    for (;;) {

        RTOS::event speakerWaitable = wait(speakerFlag + beeperFreqTimer + beeperDurTimer);

        if (speakerFlag == speakerWaitable) {

            current = speakerPool.read();
            frequency = (1000000 / current.frequency);

            duration = current.duration;
            beeperDurTimer.set(duration S);
            speakerOn = false;
            state = Beeping;

        } else if (beeperFreqTimer == speakerWaitable) {
            speakerOn = !speakerOn;

        } else if (beeperDurTimer == speakerWaitable) {
            if (speakerOn) {
                spkr.speakerOff();
                speakerOn = false;
            }
            state = SpeakerWaiting;
        }

        switch (state) {

            case SpeakerWaiting:
                //NUTHIN
                break;

            case Beeping:

                beeperFreqTimer.set(frequency US);

                if (speakerOn) {
                    spkr.speakerOn();
                } else {
                    spkr.speakerOff();
                }

                break;
        }
    }
}

void SpeakerHandler::beep(int dur, int freq) {

    temp.duration = dur;
    temp.frequency = freq;


    speakerPool.write(temp);
    speakerFlag.set();

    std::cout << "\n written to Beeper - pool: "
            << std::dec << freq
            << " HURZ and for "
            << std::dec << dur
            << " seconds ";

}